<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>在线考试系统</title>
    <style>
        .login-form {
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.5);
            border-radius: 8px;
            width: 600px;
            height: 240px;
            max-width: 100%;
            padding: 30px 35px 0;
            margin: 0%;
            position: absolute;
            top: 60%;
            left: 70%;
            margin: -180px 0 0 -220px;
            opacity: 0.8;
            filter: alpha(opacity=60);
            font: 20px;
            font-weight: bolder;
            overflow: hidden;
            background-color: white;

        }

        img {
            position: absolute;
            top: -80px;
            overflow: hidden;
        }
    </style>


</head>

<body>
    <img src="./background.jpeg" class="img_" width="2000" height="1500">

    <form class="login-form" onsubmit="login(event);">
        <label for="username">Username:</label><br>
        <input type="text" id="username" name="username" placeholder="username" required><br>
        <label for="password">Password:</label><br>
        <input type="password" id="password" name="password" placeholder="password" required><br><br>
        <input type="submit" value="Login">
    </form>

    <script>
        async function login(event) {
            event.preventDefault();
            var username = document.getElementById("username").value;
            var password = document.getElementById("password").value;

            if (isNaN(Number(username)) || username.trim() === "") {
                alert("账号只能为数字且不能为空");
                return false;
            }

            try {
                const response = await fetch('/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({ username: username, password: password }).toString(),
                });

                if (!response.ok) {
                    throw new Error('Network response was not ok: ' + response.statusText);
                }

                const data = await response.json();
                if (data.token) {
                    localStorage.setItem('authToken', data.token);
                    console.log('Token saved:', data.token);
                    // 在这里可以添加跳转到首页或其他页面的逻辑  
                    window.location.href = "/";
                    console.log("执行跳转");
                    return false; // 阻止表单默认提交行为  
                } else {
                    throw new Error('No token received from server');
                }
            } catch (error) {
                console.error('Error during login:', error);
                alert('登录失败，请重试！');
                return false;
            }
        }

        async function fetchWithToken(url, options = {}) {
            const token = localStorage.getItem('authToken');
            if (!token) {
                throw new Error('No token found in localStorage');
            }

            const headers = {
                ...options.headers,
                'Authorization': `Bearer ${token}`,
            };

            return fetch(url, {
                ...options,
                headers,
            });
        }

        // 使用示例（在实际应用中可能不会直接放在这里）  
        fetchWithToken('/login')
            .then(response => response.json())
            .then(data => console.log(data))
            .catch(error => console.error('Error fetching protected resource:', error));  
    </script>
</body>

</html>